package com.tuyrt.hi.concurrent_demo.concurrent;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 利用ReentrantReadWriteLock 来实现 多人在线文档查看与编辑的功能
 */
public class ReentrantReadWriteLockDemo {

    static class ReentrantReadWriteLockTask {

        private ReentrantReadWriteLock.ReadLock mReadLock;
        private ReentrantReadWriteLock.WriteLock mWriteLock;

        ReentrantReadWriteLock mLock = new ReentrantReadWriteLock();

        public ReentrantReadWriteLockTask() {
            mReadLock = mLock.readLock();
            mWriteLock = mLock.writeLock();
        }

        void read() {
            String name = Thread.currentThread().getName();
            try {
                mReadLock.lock();
                System.out.println("线程"+name+" 正在读取数据...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                mReadLock.unlock();
                System.out.println("线程"+name+" 释放了读锁");
            }
        }

        void write() {
            String name = Thread.currentThread().getName();
            try {
                mWriteLock.lock();
                System.out.println("线程"+name+" 正在写入数据...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                mWriteLock.unlock();
                System.out.println("线程"+name+" 释放了写锁");
            }
        }

    }

    public static void main(String[] args) {
        ReentrantReadWriteLockTask task = new ReentrantReadWriteLockTask();

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    task.read();
                }
            }).start();
        }

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    task.write();
                }
            }).start();
        }
    }
}
